package com.wlb365.admin.modules.devops.controller;

import com.wlb365.admin.bean.ServiceInstance;
import com.wlb365.admin.common.dto.R;
import com.wlb365.admin.modules.devops.dto.ServiceSearchDto;
import com.wlb365.admin.modules.devops.service.RegistryService;
import com.wlb365.admin.properties.AdminProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * <p>
 * 概述：
 * </p>
 *
 * @author zwh
 * @version 1.0
 * @copyRight 北京微利宝信息技术有限公司  All right reserved.
 * @date 2020/4/2
 */
@Slf4j
@RestController
@RequestMapping("devops/service")
public class ServiceController {
    @Autowired
    private RegistryService registryService;
    @Autowired
    private AdminProperties adminProperties;

    @RequiresPermissions("devops:service:index")
    @GetMapping("index")
    public ModelAndView index() {
        return new ModelAndView("devops/service");
    }

    @GetMapping(value = "list/data")
    public R listServiceInfo(ServiceSearchDto dto) {
        try {
            return R.ok(registryService.listAllService(1, 100));
        } catch (Exception e) {
            log.error("服务获取失败", e);
            return R.fail("服务获取失败");
        }

    }

    @RequiresPermissions("devops:service:up")
    @PostMapping(value = "up")
    public R serviceUp(ServiceInstance serviceInstance) {
        try {
            registryService.onlineInstance(serviceInstance);
            return R.ok();
        } catch (Exception e) {
            log.error("服务上线失败", e);
            return R.fail("服务上线失败");
        }
    }

    @RequiresPermissions("devops:service:down")
    @PostMapping(value = "down")
    public R serviceDown(ServiceInstance serviceInstance) {
        try {
            registryService.offlineInstance(serviceInstance);
            return R.ok();
        } catch (Exception e) {
            log.error("服务下线失败", e);
            return R.fail("服务下线失败");
        }
    }

    /**
     * 获取配置的服务信息
     */
    @GetMapping(value = "list")
    public R getServiceInfo() {
        try {
            return R.ok(adminProperties.getServiceInfo());
        } catch (Exception e) {
            log.error("服务获取失败", e);
            return R.fail("服务获取失败");
        }

    }
}
